// 创建用户信息仓库模块
import { defineStore } from "pinia";
import { Login, UserInfo, LoginOut } from "@/api/user/index";
// import type { LoginForm, loginResponseData } from "@/api/user/type";
import type { UserState } from '@/store/modules/types/type'
import { SET_TOEKN, GET_TOEKN, REMOVE_TOKEN } from "@/utils/token";
// 引入路由  (静态常量路由)
import { constantRoute } from "@/router/routes";
// 引入路由   做pinia数据持久化单独添加的
import router from '@/router/index'

// 创建用户仓库
let useUserStore = defineStore('UserStore', {
    state: (): UserState => {
        return {
            token: GET_TOEKN() as string || '',
            menuRoute: constantRoute,
            username: '',
            avatar: ''
        }
    },
    actions: {
        // 用户登录
        async userLogin(data: any) {
            let result: any = await Login(data)
            if (result.code == 200) {
                // 登录成功
                this.token = (result.data as string)
                SET_TOEKN((result.data as string))
                return 'ok'
            } else {
                // 登录失败
                return Promise.reject(new Error(result.data))
            }
        },
        // 获取用户信息
        async getUserInfo() {
            // 因为我自己单独对pinia做了持久化存储 所以将permisstion.ts文件里的获取用户信息的接口去掉了            
            let result = await UserInfo()
            if (result.code == 200) {
                this.username = result.data.name
                this.avatar = result.data.avatar
                return 'ok'
            } else {
                router.replace('/login')
                return Promise.reject(new Error(result.message))
            }
        },
        // 获取用户信息(备份)
        async getUserInfos() {
            let result = await UserInfo()
            if (result.code == 200) {
                this.username = result.data.name
                this.avatar = result.data.avatar
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        // 退出登录
        async userLoginOut() {
            let result = await LoginOut()
            if (result.code == 200) {
                // 清空store中用户数据
                this.username = ''
                this.token = ''
                this.avatar = ''
                // 清除本地存储
                REMOVE_TOKEN()
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        }

    },
    getters: {}
})

export default useUserStore